package uitl;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * @program: netty-dubbo-zhenghao
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-13 12:53
 */
//public class RpcDecoder extends ByteToMessageDecoder {
public class RpcDecoder extends ReplayingDecoder{
    //ReplayingDecoder 不需要判断数据是否足够读取，内部会进行处理判断
    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (serializer != null && clazz != null) {
/*            if (byteBuf.readableBytes() < 4) {
                return;
            }
            byteBuf.markReaderIndex();
            int dataLength = byteBuf.readInt();
            if (byteBuf.readableBytes() < dataLength) {
                byteBuf.resetReaderIndex();
                return;
            }
            byte[] bytes = new byte[dataLength];
            byteBuf.readBytes(bytes);
            out.add(serializer.deserialize(clazz, bytes));*/
            byte[] bytes = new byte[byteBuf.readInt()];
            byteBuf.readBytes(bytes);
            out.add(serializer.deserialize(clazz, bytes));
        }
    }
}
